﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using IGGCore;
using IGGWindowApp.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Globalization;

namespace IGGWindowApp
{
    public class FormManagerBeta
    {
        // PROPERTIES
        public MainFormBeta MainFormBeta { get; set; }

        // VARIABLES
        private MainChannel m_mainChannel;
        private StadiumParser m_stadiumParser;
        private GameRandomizer m_gameRandomizer;

        private bool m_uiInitialized = false;
        private bool m_firstTwitter = true;
        private bool m_firstStars = true;
        private bool m_running = false;
        private DateTime m_currentDate = DateTime.Now;
        private CultureInfo m_CultureEnCa = new CultureInfo("en-CA");

        // THREADS
        private Thread m_initThread;
        private Thread m_newsThread;
        private Thread m_twitterThread;
        private Thread m_transactionsThread;
        private Thread m_tickerThread;
        private Thread m_scoreboardThread;
        private Thread m_standingsThread;
        
        /// <summary>
        /// Form Manager Constructor
        /// </summary>
        public FormManagerBeta()
        {
            m_mainChannel = new MainChannel();
            MainFormBeta = new MainFormBeta();
            m_stadiumParser = new StadiumParser();
            m_gameRandomizer = new GameRandomizer();

            if (ToolBox.YesterdayScores())
            {
                m_currentDate = m_currentDate.AddDays(-1);
            }

            MainFormBeta.MainFormLoaded += new EventHandler(MainFormBeta_MainFormLoaded);
            MainFormBeta.MainFormClosed += new EventHandler(MainFormBeta_MainFormClosed);
            MainFormBeta.URLClicked += new IGGWindowApp.MainFormBeta.URLClickedHandler(MainFormBeta_URLClicked);
            MainFormBeta.TeamRequested += new IGGWindowApp.MainFormBeta.TeamRequestHandler(MainFormBeta_TeamRequested);
            MainFormBeta.GameSelected += new IGGWindowApp.MainFormBeta.GameSelectedHandler(MainFormBeta_GameSelected);
        }

        private void MainFormBeta_MainFormLoaded(object sender, EventArgs e)
        {
            //m_initThread = new Thread(new ThreadStart(InitializeApp));
            //m_initThread.Start();


            m_running = true;
            UpdateUI(MainFormBeta.UIACTIONS.INITLOG, new object[] { });
            UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing main title..." });
            UpdateUI(MainFormBeta.UIACTIONS.TITLE, new object[] { GetAppTitle() });
            UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing twitter..." });
            UpdateUI(MainFormBeta.UIACTIONS.INITTWITTER, new object[] { });
            UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing transactions..." });
            UpdateUI(MainFormBeta.UIACTIONS.INITRANS, new object[] { });
            UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing stars..." });
            UpdateUI(MainFormBeta.UIACTIONS.INITSTARS, new object[] { });
            UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing scoreboard..." });
            UpdateUI(MainFormBeta.UIACTIONS.INITSCOREBOARD, new object[] { });
            UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing news..." });
            UpdateUI(MainFormBeta.UIACTIONS.INITNEWS, new object[] { });
            UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing header..." });
            UpdateUI(MainFormBeta.UIACTIONS.INITHEADER, new object[] { });
            UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing navigator..." });
            UpdateUI(MainFormBeta.UIACTIONS.INITNAVIGATOR, new object[] { });
            UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing status bar..." });
            UpdateUI(MainFormBeta.UIACTIONS.INITSTATUS, new object[] { });
            UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing stadium..." });
            UpdateUI(MainFormBeta.UIACTIONS.INITSTADIUM, new object[] { });
            UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing stats..." });
            UpdateUI(MainFormBeta.UIACTIONS.INITSTATS, new object[] { });
            UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing standings..." });
            UpdateUI(MainFormBeta.UIACTIONS.INITSTANDINGS, new object[] { });
            //UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing Web..." });
            //UpdateUI(MainFormBeta.UIACTIONS.INITWEB, new object[] { });

            m_scoreboardThread = new Thread(new ThreadStart(LoadScoreboard));
            m_scoreboardThread.Start();

            m_newsThread = new Thread(new ThreadStart(LoadNews));
            m_newsThread.Start();

            //LoadScoreboard();
            m_twitterThread = new Thread(new ThreadStart(LoadTwitter));
            m_twitterThread.Start();

            m_transactionsThread = new Thread(new ThreadStart(LoadTransactions));
            m_transactionsThread.Start();
            

            //m_tickerThread = new Thread(new ThreadStart(ManageTicker));
            //m_tickerThread.Start();

            m_standingsThread = new Thread(new ThreadStart(LoadStandings));
            m_standingsThread.Start();
        }

        /// <summary>
        /// Initialiation of the main form ui parts
        /// </summary>
        private void InitializeApp()
        {
            m_running = true;
            UpdateUI(MainFormBeta.UIACTIONS.INITLOG, new object[] { });
            UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing main title..." });
            UpdateUI(MainFormBeta.UIACTIONS.TITLE, new object[] { "IGG " + DateTime.Now.ToString("dddd d MMMM yyyy") });
            UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing twitter..." });
            UpdateUI(MainFormBeta.UIACTIONS.INITTWITTER, new object[] { });
            UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing transactions..." });
            UpdateUI(MainFormBeta.UIACTIONS.INITRANS, new object[] { });
            UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing game panel..." });
            //UpdateUI(MainFormBeta.UIACTIONS.INITINGAME, new object[] { });
            //UpdateUI(MainFormBeta.UIACTIONS.INITNAVIGATOR, new object[] { });
            //UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing status..." });
            //UpdateUI(MainFormBeta.UIACTIONS.INITSTATUS, new object[] { });
            //UpdateUI(MainFormBeta.UIACTIONS.SWITCHDOWN, new object[] { });
            //UpdateUI(MainFormBeta.UIACTIONS.SWITCHLOADING, new object[] { MainFormBeta.ZONES.SOUTH, false });
            //UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing header..." });
            //UpdateUI(MainFormBeta.UIACTIONS.INITHEADER, new object[] { });
            //UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing scoreboard..." });
            //UpdateUI(MainFormBeta.UIACTIONS.INITSCOREBOARD, new object[] { });
            //UpdateUI(MainFormBeta.UIACTIONS.INITSTADIUM, new object[] { });
            //UpdateUI(MainFormBeta.UIACTIONS.INITSTARS, new object[] { });
            //UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Initializing news..." });
            //UpdateUI(MainFormBeta.UIACTIONS.INITNEWS, new object[] { });
            //UpdateUI(MainFormBeta.UIACTIONS.INITWEB, new object[] { });
            //UpdateUI(MainFormBeta.UIACTIONS.INITSTATS, new object[] { });
            //UpdateUI(MainFormBeta.UIACTIONS.INITSTANDINGS, new object[] { });
            //UpdateUI(MainFormBeta.UIACTIONS.SWITCHUP, new object[] { "HEADER" });
            //UpdateUI(MainFormBeta.UIACTIONS.SWITCHLOADING, new object[] { MainFormBeta.ZONES.NORTH, false });
            m_uiInitialized = true;
        }

        #region events management

        private void MainFormBeta_GameSelected(Game game)
        {
            UpdateUI(MainFormBeta.UIACTIONS.SWITCHCENTRAL, new object[] { "STADIUM" });
            m_mainChannel.ScoreBoard.SelectedGame = game;
            WindowStadium stadium = m_stadiumParser.GetStadium(game.Stadium);
            UpdateUI(MainFormBeta.UIACTIONS.UPDATESTADIUM, new object[] { stadium, game });
            
            //LoadGameBoxscore();
            UpdateUI(MainFormBeta.UIACTIONS.UPDATESCOREBOARD, new object[] { game });
            UpdateUI(MainFormBeta.UIACTIONS.SWITCHUP, new object[] { "SCOREBOARD" });

            if (game.Status.Indicator.Category == Indicator.IndicatorCategoy.IN_PROGRESS
                || game.Status.Indicator.Category == Indicator.IndicatorCategoy.INTERRUPTED)
            {
                if (LoadGameAlignment() == false)
                {
                    //Log("The selected game alignment cannot be loaded. Try later.");
                    return;
                }
                UpdateUI(MainFormBeta.UIACTIONS.SWITCHLEFT, new object[] { "GAME" });
                UpdateUI(MainFormBeta.UIACTIONS.UPDATEINGAME, new object[] { game, GetBoxscore(game), new Player[]{} });
                string battingCity = m_mainChannel.ScoreBoard.SelectedGame.AwayTeam.Name;
                string pitchingCity = m_mainChannel.ScoreBoard.SelectedGame.HomeTeam.Name;
                if (m_mainChannel.ScoreBoard.SelectedGame.Status.InningTop == false)
                {
                    battingCity = m_mainChannel.ScoreBoard.SelectedGame.HomeTeam.Name;
                    pitchingCity = m_mainChannel.ScoreBoard.SelectedGame.AwayTeam.Name;
                }
                UpdateUI(MainFormBeta.UIACTIONS.UPDATEPICS, new object[] { PlayerParser.DownloadPlayerPicture(m_mainChannel.ScoreBoard.SelectedGame.Status.CurrentPitcher.Id), 
                    PlayerParser.DownloadPlayerPicture(m_mainChannel.ScoreBoard.SelectedGame.Status.CurrentBatter.Id) });
            }
            else if (game.Status.Indicator.Category == Indicator.IndicatorCategoy.TERMINATED)
            {
                Player[] stars = ThreeStarsCalculator.GetThreeStarPlayers(m_mainChannel.ScoreBoard.SelectedGame, true);

                stars[0].Pic = PlayerParser.DownloadPlayerPicture(stars[0].Id);
                stars[1].Pic = PlayerParser.DownloadPlayerPicture(stars[1].Id);
               // UpdateUI(MainFormBeta.UIACTIONS.UPDATESTARS, new object[] { stars });
                UpdateUI(MainFormBeta.UIACTIONS.UPDATEINGAME, new object[] { game, GetBoxscore(game), stars });
                UpdateUI(MainFormBeta.UIACTIONS.SWITCHLEFT, new object[] { "GAME" });
            }
        }

        private void MainFormBeta_URLClicked(string url)
        {
            UpdateUI(MainFormBeta.UIACTIONS.NAVIGATE, new object[] { url });
        }

        private void MainFormBeta_TeamRequested(string team)
        {
            if (team == null)
            {
                m_mainChannel.ScoreBoard.ActiveTeam = new Team();
                m_mainChannel.ScoreBoard.ActiveTeam.Code = TeamCruncher.GetRandomCode();
                m_mainChannel.UpdateDepthChart();
            }
            UpdateUI(MainFormBeta.UIACTIONS.UPDATETEAM, new object[] { m_mainChannel.ScoreBoard.ActiveTeam });
        }



        private string GetAppTitle()
        {
            string title = "IGG " + DateTime.Now.ToString("dddd MMMM d, yyyy", m_CultureEnCa);
            
            return title;
        }

        private void MainFormBeta_MainFormClosed(object sender, EventArgs e)
        {
            m_running = false;
            m_twitterThread.Abort();
            //m_scoreboardThread.Abort();
            //m_tickerThread.Abort();
            m_transactionsThread.Abort();
            m_newsThread.Abort();
        }

        #endregion





        /// <summary>
        /// BeginInvoke wrapper for main form delegates
        /// </summary>
        private void UpdateUI(MainFormBeta.UIACTIONS action, object[] args)
        {
            if (m_running)
            {
                MainFormBeta.BeginInvoke(MainFormBeta.myUpdateUI, new object[] { action, args });
            }
        }

        private string GetGameTicker(int idx)
        {
            string tickertext = "";

            if (m_mainChannel.ScoreBoard.GamesList.SortedGames.Count >= idx && idx>0)
            {
                if (m_mainChannel.ScoreBoard.GamesList.SortedGames[idx].Status.Indicator.IsInProgress
                    || m_mainChannel.ScoreBoard.GamesList.SortedGames[idx].Status.Indicator.IsInterrupted
                    || m_mainChannel.ScoreBoard.GamesList.SortedGames[idx].Status.Indicator.IsTerminated)
                {
                    tickertext += m_mainChannel.ScoreBoard.GamesList.SortedGames[idx].AwayTeam.Name + " "
                        + m_mainChannel.ScoreBoard.GamesList.SortedGames[idx].AwayScore + " - "
                        + m_mainChannel.ScoreBoard.GamesList.SortedGames[idx].HomeTeam.Name + " "
                        + m_mainChannel.ScoreBoard.GamesList.SortedGames[idx].HomeScore;
                }
            }
            return tickertext;
        }

        private string GetBoxscore(Game selectedGame)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(ToolBox.GetFormattedStringPadLeft("AB", 19));
            sb.Append(ToolBox.GetFormattedStringPadLeft("R", 2));
            sb.Append(ToolBox.GetFormattedStringPadLeft("H", 3));
            sb.Append(ToolBox.GetFormattedStringPadLeft("RBI", 5));
            sb.Append(ToolBox.GetFormattedStringPadLeft("AVG", 6));
            sb.Append(Environment.NewLine);
            foreach (Player player in selectedGame.Boxscore.AwayBatting)
            {
                string prefix = "";
                if (String.IsNullOrEmpty(player.BO) == false)
                {
                    if (player.BO[2] == '1')
                    {
                        prefix = "- ";
                    }
                    else if (player.BO[2] == '2')
                    {
                        prefix = "-- ";
                    }
                    else if (player.BO[2] == '3')
                    {
                        prefix = "--- ";
                    }
                }
                sb.Append(ToolBox.GetFormattedStringPadRight(prefix + player.LastName, 16));
                sb.Append(ToolBox.GetFormattedStringPadLeft(player.Ab.ToString(), 2));
                sb.Append(" ");
                sb.Append(ToolBox.GetFormattedStringPadLeft(player.R.ToString(), 2));
                sb.Append(" ");
                sb.Append(ToolBox.GetFormattedStringPadLeft(player.Hits.ToString(), 2));
                sb.Append(" ");
                sb.Append(ToolBox.GetFormattedStringPadLeft(player.RBI.ToString(), 3));
                sb.Append("   ");
                sb.Append(player.AVG.ToString() + Environment.NewLine);
            }
            sb.Append(Environment.NewLine);
            foreach (Player player in selectedGame.Boxscore.HomeBatting)
            {
                string prefix = "";
                if (String.IsNullOrEmpty(player.BO) == false)
                {
                    if (player.BO[2] == '1')
                    {
                        prefix = "- ";
                    }
                    else if (player.BO[2] == '2')
                    {
                        prefix = "-- ";
                    }
                    else if (player.BO[2] == '3')
                    {
                        prefix = "--- ";
                    }
                }
                sb.Append(ToolBox.GetFormattedStringPadRight(prefix + player.LastName, 16));
                sb.Append(ToolBox.GetFormattedStringPadLeft(player.Ab.ToString(), 2));
                sb.Append(" ");
                sb.Append(ToolBox.GetFormattedStringPadLeft(player.R.ToString(), 2));
                sb.Append(" ");
                sb.Append(ToolBox.GetFormattedStringPadLeft(player.Hits.ToString(), 2));
                sb.Append(" ");
                sb.Append(ToolBox.GetFormattedStringPadLeft(player.RBI.ToString(), 3));
                sb.Append("   ");
                sb.Append(player.AVG.ToString() + Environment.NewLine);
            }
            sb.Append(Environment.NewLine);
            sb.Append(ToolBox.GetFormattedStringPadLeft("IP", 17));
            sb.Append(ToolBox.GetFormattedStringPadLeft("H", 3));
            sb.Append(ToolBox.GetFormattedStringPadLeft("ER", 4));
            sb.Append(ToolBox.GetFormattedStringPadLeft("BB", 3));
            sb.Append(ToolBox.GetFormattedStringPadLeft("SO", 3));
            sb.Append(ToolBox.GetFormattedStringPadLeft("ERA", 5));
            sb.Append(Environment.NewLine);
            foreach (Player player in selectedGame.Boxscore.AwayPitching)
            {
                if (player.Report == null)
                {
                    sb.Append(ToolBox.GetFormattedStringPadRight(player.LastName, 14));
                }
                else
                {
                    sb.Append(ToolBox.GetFormattedStringPadRight(player.LastName + " " + player.Report, 14));
                }
                sb.Append(player.IP);
                sb.Append(" ");
                sb.Append(ToolBox.GetFormattedStringPadLeft(player.Hits.ToString(), 2));
                sb.Append(" ");
                sb.Append(ToolBox.GetFormattedStringPadLeft(player.EarnedRuns.ToString(), 2));
                sb.Append(" ");
                sb.Append(ToolBox.GetFormattedStringPadLeft(player.BB.ToString(), 2));
                sb.Append(" ");
                sb.Append(ToolBox.GetFormattedStringPadLeft(player.StrikeOuts.ToString(), 2));
                sb.Append("  ");
                sb.Append(player.ERA.ToString());
                sb.Append(Environment.NewLine);
            }
            sb.Append(Environment.NewLine);
            foreach (Player player in selectedGame.Boxscore.HomePitching)
            {
                if (player.Report == null)
                {
                    sb.Append(ToolBox.GetFormattedStringPadRight(player.LastName, 14));
                }
                else
                {
                    sb.Append(ToolBox.GetFormattedStringPadRight(player.LastName + " " + player.Report, 14));
                }
                sb.Append(player.IP);
                sb.Append(" ");
                sb.Append(ToolBox.GetFormattedStringPadLeft(player.Hits.ToString(), 2));
                sb.Append(" ");
                sb.Append(ToolBox.GetFormattedStringPadLeft(player.EarnedRuns.ToString(), 2));
                sb.Append(" ");
                sb.Append(ToolBox.GetFormattedStringPadLeft(player.BB.ToString(), 2));
                sb.Append(" ");
                sb.Append(ToolBox.GetFormattedStringPadLeft(player.StrikeOuts.ToString(), 2));
                sb.Append("  ");
                sb.Append(player.ERA.ToString());
                sb.Append(Environment.NewLine);
            }
            return sb.ToString();
        }

        private void ManageTicker()
        {
            Random rnd = new Random();
            string emptyspace = "         ";
            Thread.Sleep(8000);
            string tickertext = "";
            while (m_running)
            {
                tickertext = "";
                tickertext += GetGameTicker(0);
                if (rnd.Next(10) < 4)
                {
                    m_mainChannel.UpdateHistory();
                    tickertext += emptyspace + m_mainChannel.ScoreBoard.History[0];
                }
                if (m_mainChannel.ScoreBoard.News != null && m_mainChannel.ScoreBoard.News.Count > 0)
                {
                    if (rnd.Next(10) < 8)
                    {
                        tickertext += emptyspace + m_mainChannel.ScoreBoard.News[0].Title;
                    }
                    else
                    {
                        tickertext += emptyspace + m_mainChannel.ScoreBoard.News[rnd.Next(m_mainChannel.ScoreBoard.News.Count)].Title;
                    }
                }
                tickertext += emptyspace + GetGameTicker(1);
                if (m_mainChannel.ScoreBoard.Tweets != null && m_mainChannel.ScoreBoard.Tweets.Length > 0)
                {
                    tickertext += emptyspace + m_mainChannel.ScoreBoard.Tweets[0].Author + " : " + m_mainChannel.ScoreBoard.Tweets[0].Text;
                }
                tickertext += emptyspace + GetGameTicker(2);
                tickertext += emptyspace + m_mainChannel.ScoreBoard.News[rnd.Next(m_mainChannel.ScoreBoard.News.Count)].Title;
                tickertext += emptyspace + GetGameTicker(3);
                if (m_mainChannel.ScoreBoard.Transactions != null && m_mainChannel.ScoreBoard.Transactions.Count > 0)
                {
                    tickertext += emptyspace + m_mainChannel.ScoreBoard.Transactions[0].Transactions[0].Player
                        + " (" + m_mainChannel.ScoreBoard.Transactions[0].Transactions[0].Team + ") "
                        + m_mainChannel.ScoreBoard.Transactions[0].Transactions[0].Action;
                }
                tickertext += emptyspace + GetGameTicker(4);
                UpdateUI(MainFormBeta.UIACTIONS.UPDATETICKER, new object[] { tickertext });
                Thread.Sleep(8000);
            }
        }

        /// <summary>
        /// Load twitter
        /// </summary>
        private void LoadTwitter()
        {
            //while (m_uiInitialized == false)
            //{
            //    Thread.Sleep(100);
            //}
            Thread.Sleep(3000);
            while (m_running)
            {
                if (ToolBox.YesterdayScores())
                {
                    m_currentDate = DateTime.Now.AddDays(-1);
                }
                else
                {
                    m_currentDate = DateTime.Now;
                }
                int currentTry = 1;
                int delay = 1000;
                bool success = false;
                while (success == false && currentTry <= WindowConstants.MAX_TRIES)
                {
                    try
                    {
                        UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Loading twitter statuses..." });
                        m_mainChannel.UpdateTweets();
                        success = true;
                        UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "The statuses have been successfully loaded." });
                    }
                    catch (Exception ex)
                    {
                        UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { ex.Message });
                        Thread.Sleep(delay);
                        delay = (delay * 2);
                    }
                    currentTry++;
                }
                if (success && m_mainChannel.ScoreBoard.Tweets!=null)
                {
                    UpdateUI(MainFormBeta.UIACTIONS.UPDATETWITTER, new object[] { m_mainChannel.ScoreBoard.Tweets });
                    if (m_firstTwitter)
                    {
                        m_firstTwitter = false;
                        UpdateUI(MainFormBeta.UIACTIONS.SWITCHLEFT, new object[] { "TWITTER" });
                    }
                }
                Thread.Sleep(60000);
            }
        }

        /// <summary>
        /// Load the transactions
        /// </summary>
        private void LoadStandings()
        {
            Thread.Sleep(8000);
            int currentTry = 1;
            int delay = 3000;
            bool success = false;
            while (success == false && currentTry <= WindowConstants.MAX_TRIES)
            {
                try
                {
                    UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Loading standings..." });
                    m_mainChannel.UpdateStandings();
                    success = true;
                    UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "The standings have been successfully loaded." });
                }
                catch (Exception ex)
                {
                    UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Unable to load the standings." });
                    Thread.Sleep(delay);
                    delay = (delay * 2);
                }
                currentTry++;
            }
            if (success)
            {
                UpdateUI(MainFormBeta.UIACTIONS.UPDATESTANDINGS, new object[] { m_mainChannel.ScoreBoard });
            }
        }

        /// <summary>
        /// Load the transactions
        /// </summary>
        private void LoadTransactions()
        {
            Thread.Sleep(5000);
            int currentTry = 1;
            int delay = 1000;
            bool success = false;
            while (success == false && currentTry <= WindowConstants.MAX_TRIES)
            {
                try
                {
                    UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Loading transactions..." });
                    m_mainChannel.UpdateTransactions();
                    success = true;
                    UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "The transactions have been successfully loaded." });
                }
                catch (Exception ex)
                {
                    UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { ex.Message });
                    Thread.Sleep(delay);
                    delay = (delay * 2);
                }
                currentTry++;
            }
            if (success)
            {

                UpdateUI(MainFormBeta.UIACTIONS.UPDATETRANS, new object[] { m_mainChannel.ScoreBoard.Transactions });
            }
        }

        private void LoadDailyStars()
        {
            if (m_mainChannel.ScoreBoard.GamesList.Games.Count == 0)
            {
                return;
            }
            m_mainChannel.UpdateAllBoxscores(m_currentDate, m_mainChannel.ScoreBoard);
            Player[] stars = ThreeStarsCalculator.GetThreeStarPlayers(m_mainChannel.ScoreBoard.GamesList.Games);

            if (stars[0] != null)
            {
                stars[0].Pic = PlayerParser.DownloadPlayerPicture(stars[0].Id);
                stars[1].Pic = PlayerParser.DownloadPlayerPicture(stars[1].Id);
                stars[2].Pic = PlayerParser.DownloadPlayerPicture(stars[2].Id);
                stars[3].Pic = PlayerParser.DownloadPlayerPicture(stars[3].Id);
                UpdateUI(MainFormBeta.UIACTIONS.UPDATESTARS, new object[] { stars });

                if (m_firstStars)
                {
                    UpdateUI(MainFormBeta.UIACTIONS.SWITCHLEFT, new object[] { "STARS" });
                    m_firstStars = false;
                }
            }
        }

        /// <summary>
        /// Load the main scoreboard
        /// </summary>
        private void LoadScoreboard()
        {
            //while (m_running)
            //{
                bool success = false;
                int currentTry = 1;
                int delay = 1000;
                while (success == false && currentTry <= WindowConstants.MAX_TRIES)
                {
                    try
                    {
                        UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Loading mlb.com scoreboard..." });
                        if (m_mainChannel.ScoreBoard.SelectedGame == null)
                        {
                            m_mainChannel.RefreshScoreboard(m_currentDate, null);
                        }
                        else
                        {
                            m_mainChannel.RefreshScoreboard(m_currentDate, m_mainChannel.ScoreBoard.SelectedGame.Id);
                        }
                        success = true;
                        UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "The scoreboard has been successfully parsed." });
                        UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "There are " + m_mainChannel.ScoreBoard.GamesList.Games.Count + " games" });
                        Thread.Sleep(delay);
                    }
                    catch (Exception ex)
                    {
                        UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { ex.Message });
                        delay = (delay * 2);
                    }
                    currentTry++;
                }
                if (success == true)
                {
                    UpdateUI(MainFormBeta.UIACTIONS.UPDATENAVIGATOR, new object[] { m_mainChannel.ScoreBoard });
                    //UpdateUI(MainFormBeta.UIACTIONS.SWITCHRIGHT, new object[] { });
                    LoadDailyStars();
                }
                //Thread.Sleep(60000);
            //}

        }

        /// <summary>
        /// Load game alignment
        /// </summary>
        private bool LoadGameAlignment()
        {
            bool success = false;
            int currentTry = 1;
            int delay = 1000;
            while (success == false && currentTry <= WindowConstants.MAX_TRIES)
            {
                try
                {
                    Thread.Sleep(delay);
                    //Log("Retrieving selected game team alignment...");
                    m_mainChannel.UpdateTeamAlignment(m_currentDate);
                    success = true;
                    //Log("The alignment has been successfully parsed.");
                }
                catch (Exception ex)
                {
                    //Log(ex.Message);
                    delay = (delay * 2);
                }
                currentTry++;
            }
            return success;
        }

        private bool LoadGameBoxscore()
        {
            bool success = false;
            int currentTry = 1;
            int delay = 1000;
            while (success == false && currentTry <= WindowConstants.MAX_TRIES)
            {
                try
                {
                    Thread.Sleep(delay);
                    //Log("Retrieving selected game boxscore...");
                    m_mainChannel.UpdateBoxscore(m_currentDate);
                    success = true;
                    //Log("The boxscore has been successfully parsed.");
                }
                catch (Exception ex)
                {
                    //Log(ex.Message);
                    delay = (delay * 2);
                }
                currentTry++;
            }
            return success;
        }

        /// <summary>
        /// Load the news
        /// </summary>
        private void LoadNews()
        {
            int currentTry = 1;
            int delay = 2000;
            bool success = false;
            Thread.Sleep(1500);
            while (success == false && currentTry <= WindowConstants.MAX_TRIES)
            {
                try
                {
                    UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Loading mlb.com news..." });
                    m_mainChannel.UpdateNews(false);
                    if (m_mainChannel.ScoreBoard.News.Count > 0)
                    {
                        success = true;
                        UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "The news have been successfully loaded." });
                    }
                    else
                    {
                        UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { "Unable to load the news." });
                        Thread.Sleep(delay);
                        delay = (delay * 2);
                    }

                }
                catch (Exception ex)
                {
                    UpdateUI(MainFormBeta.UIACTIONS.ADDLOG, new object[] { ex.Message });
                    Thread.Sleep(delay);
                    delay = (delay * 2);
                }
                currentTry++;
            }
            if (success)
            {
                UpdateUI(MainFormBeta.UIACTIONS.UPDATEHEADER, new object[] { m_mainChannel.ScoreBoard.News[0] });
                UpdateUI(MainFormBeta.UIACTIONS.UPDATENEWS, new object[] { m_mainChannel.ScoreBoard.News });
            }
        }
    }
}
